layui.define(['table', 'form', 'jquery'], function (exports) {
    var MOD_NAME = 'tableSelect',
        table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        tableSelect = function () { };

    tableSelect.prototype.options = {
        elem: '#id',
        checkedKey: 'id', //表格的唯一建值，影响到选中状态
        searchKey: 'keyword',
        searchPlaceholder: '关键词搜索',
        search: [],
        table: {},
        v: '1.0.1'
    }

    /**
     * 初始化表格选择器
     */
    tableSelect.prototype.render = function (opt) {
        var options = $.extend(this.options, opt);
        var elem = $(options.elem);
        $('div.tableSelect').remove();
        options.table.width = options.table.width ? options.table.width : Math.min($(window).width() - 20, Math.max($(window).width() * 0.618, 480));
        var t = elem.offset().top + elem.outerHeight() + "px";
        var l = elem.offset().left + "px";
        var tableName = "tableSelect_table_" + new Date().getTime();
        var tableBox = '<style type="text/css">.tableSelectBar .layui-input, .layui-select, .layui-textarea{height: 30px;}.tableSelectBar .layui-form-select dl{top:34px;}.layui-form{margin-top:0}.tableSelectBar .layui-form-select dl dd, .tableSelectBar .layui-form-select dl dt{line-height:28px;}</style>';
        tableBox += '<div class="tableSelect layui-anim layui-anim-upbit" style="left:' + l + ';top:' + t + ';border: 1px solid #d2d2d2;background-color: #fff;box-shadow: 0 2px 4px rgba(0,0,0,.12);padding:10px 10px 0 10px;position: absolute;z-index: 900;margin: 5px 0;border-radius: 2px;">';
        tableBox += '<div class="tableSelectBar">';
        tableBox += '<form class="layui-form" action="" lay-filter="' + tableName + '" style="width:' + options.table.width + 'px;">';
        tableBox += '<div class="layui-form-item" style="margin-bottom:5px;">';
        if (options.search.length) {
            var arr = [];
            options.search.forEach(function (item, index) {
                arr.push('<div class="layui-inline">');
                arr.push('<div class="layui-input-inline">');
                if (item.type === 'text') {
                    arr.push('<input type="text" name="' + item.key + '" placeholder="' + item.placeholder + '"' + (item.disabled == '1' ? ' disabled' : '') + ' autocomplete="off" class="layui-input">')
                } else if (item.type === 'select') {
                    arr.push('<select name="' + item.key + '">');
                    arr.push('<option value="">' + item.placeholder + '：全部</option>');
                    if (item.data) {
                        item.data.forEach(function (x, j) {
                            arr.push('<option value="' + x.key + '"' + (x.disabled == '1' ? ' disabled' : '') + '>' + x.value + '</option>');
                        });
                    }
                    arr.push('</select>');
                }
                arr.push('</div>');
                arr.push('</div>');
            });
            tableBox += arr.join('');
        } else {
            tableBox += '<div class="layui-inline">';
            tableBox += '<div class="layui-input-inline">';
            tableBox += '<input type="text" name="' + options.searchKey + '" placeholder="' + options.searchPlaceholder + '" autocomplete="off" class="layui-input">';
            tableBox += '</div>';
            tableBox += '</div>';
        }
        tableBox += '<div class="layui-inline">';
        tableBox += '<button class="layui-btn layui-btn-primary layui-btn-sm tableSelect_btn_search" lay-submit lay-filter="tableSelect_btn_search"><i class="layui-icon layui-icon-search"></i></button>';
        tableBox += '<button class="layui-btn layui-btn-sm tableSelect_btn_select" type="button">选择</button>';
        tableBox += '</div>';
        tableBox += '</div>';
        tableBox += '</form>';
        tableBox += '<table id="' + tableName + '" lay-filter="' + tableName + '"></table>';
        tableBox += '</div>';
        tableBox += '</div>';
        tableBox = $(tableBox);
        $('body').append(tableBox);

        //渲染TABLE
        options.table.elem = "#" + tableName;

        //回显呈现选中效果
        options.table.done = function (res, curr, count) {
            form.render('select', tableName);
            var data = elem.attr('ts-selected') || '';
            var checkData = data.split(",");
            for (var i = 0; i < res.data.length; i++) {
                for (var j = 0; j < checkData.length; j++) {
                    if (res.data[i].id == checkData[j]) {
                        res.data[i]["LAY_CHECKED"] = 'true';
                        var index = res.data[i]['LAY_TABLE_INDEX'];
                        var checkbox = $('#' + tableName + '').next().find('tr[data-index=' + index + '] input[type="checkbox"]');
                        checkbox.prop('checked', true).next().addClass('layui-form-checked');
                        var radio = $('#' + tableName + '').next().find('tr[data-index=' + index + '] input[type="radio"]');
                        radio.prop('checked', true).next().addClass('layui-form-radioed').find("i").html('&#xe643;');
                    }
                }
                //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
                var checkStatus = table.checkStatus('' + tableName + '');
                if (checkStatus.isAll) {
                    $('#' + tableName + '').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                    $('#' + tableName + '').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                }
            }
        }

        var tableSelect_table = table.render(options.table);

        //关键词搜索
        form.on('submit(tableSelect_btn_search)', function (data) {
            tableSelect_table.reload({
                where: options.table.where && 'search' in options.table.where ? {
                    search: data.field
                } : data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });

        //双击行选中
        table.on('rowDouble(' + tableName + ')', function (obj) {
            var checkStatus = { data: [obj.data] };
            var ids = [];
            $.each(checkStatus.data, function (i, item) {
                ids.push(item[options.checkedKey]);
            });
            elem.attr('ts-selected', ids.join(','));
            opt.done(elem, checkStatus.data);
            tableBox.remove();
        });

        //按钮选中
        tableBox.find('.tableSelect_btn_select').on('click', function () {
            var checkStatus = table.checkStatus('' + tableName + '');
            var ids = [];
            $.each(checkStatus.data, function (i, item) {
                ids.push(item[options.checkedKey]);
            });
            elem.attr('ts-selected', ids.join(','));
            opt.done(elem, checkStatus.data);
            tableBox.remove();
        });

        //点击其他区域关闭
        $(document).mouseup(function (e) {
            var userSet_con = $('' + opt.elem + ',.tableSelect');
            if (!userSet_con.is(e.target) && userSet_con.has(e.target).length === 0) {
                tableBox.remove();
            }
        });
    }

    /**
     * 隐藏选择器
     */
    tableSelect.prototype.hide = function () {
        $('.tableSelect').remove();
    }

    //自动完成渲染
    var tableSelect = new tableSelect();

    //FIX 滚动时错位
    if (window.top == window.self) {
        $(window).scroll(function () {
            tableSelect.hide();
        });
    }

    // 有空实现，跨页选数据
    exports(MOD_NAME, tableSelect);
});